package com.wjy.common.resttemplate;

import com.wjy.common.global.ThreadLocalEnv;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;

/**
 * @author wjy
 * @desc RestTemplate监听
 * @data 2019年4月24日
 */
@Log4j2
@Component
public class RestRequestInterceptor implements ClientHttpRequestInterceptor {

    @Autowired
    private ThreadLocalEnv threadLocalEnv;

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] bs, ClientHttpRequestExecution execution)
            throws IOException {
        URI uri = request.getURI();
        HttpMethod method = request.getMethod();
        String body = new String(bs);
        log.info("requestURI: " + uri);
        log.info("requestMETHOD: " + method);
        log.info("requestBODY: " + body);
        HttpHeaders headers = request.getHeaders();
        headers.add("H-AuthorId", threadLocalEnv.getENV().getAuthor_id());
        headers.add("H-Token", threadLocalEnv.getENV().getToken());
        ClientHttpResponse response = execution.execute(request, bs);
        return response;
    }

}
